# Create your views here.
from django.http import HttpResponse
from django.template import Context, loader
from goals.models import Plan
from django.conf import settings
from datetime import date
from goals.forms import GoalForm
from goals.models import Goal
from goals.models import Plan, PlanStatus

from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.forms.models import inlineformset_factory
from datetime import datetime
def today(request):
    if not request.user.is_authenticated():
      return HttpResponse("No access!");
    else:
      td = date.today()
      today_plan_list_tmp = Plan.objects.filter(user = request.user.username)\
      .filter(deadline__gte = date.today() ).filter(frequency = 1)
      #for plan in today_plan_list
      today_plan_list = []
      for plan in today_plan_list_tmp:
          day = datetime.now().timetuple().tm_yday 
          pstatus = PlanStatus.objects.filter(plan = plan).filter(updateIndex = day)
          if not pstatus:
            today_plan_list.append(plan)
       
      t = loader.get_template('myplans.html')
      c = Context({
        'today_plan_list': today_plan_list,
        'user':request.user,
        'plan_count':len(today_plan_list),
      })
      return HttpResponse(t.render(c))

def weekly(request):
    if not request.user.is_authenticated():
      return HttpResponse("No access!");
    else:
      td = date.today()
      today_plan_list_tmp = Plan.objects.filter(user = request.user.username)\
      .filter(deadline__gte = date.today() ).filter(frequency = 2)
      #for plan in today_plan_list
      today_plan_list = []
      for plan in today_plan_list_tmp:
          week = datetime.now().isocalendar()[1] 
          pstatus = PlanStatus.objects.filter(plan = plan).filter(updateIndex = week)
          if not pstatus:
            today_plan_list.append(plan)
       
      t = loader.get_template('myplans.html')
      c = Context({
        'today_plan_list': today_plan_list,
        'user':request.user,
        'plan_count':len(today_plan_list),
      })
      return HttpResponse(t.render(c))

def get_plans(request):
    if not request.user.is_authenticated():
      return HttpResponse("No access!");
    else:
      list = request.GET.get('list', '')
      frequency = 0
      updateIndex = -1
      if list == "today":
         frequency = 1
         updateIndex = datetime.now().timetuple().tm_yday 
      elif list == "weekly":
         frequency = 2
         updateIndex = datetime.now().isocalendar()[1]
      elif list == "monthly":
         frequency = 3
         updateIndex = datetime.now().month
      else:
         updateIndex = -1   
      td = date.today()
      today_plan_list_tmp = Plan.objects.filter(user = request.user.username)\
      .filter(deadline__gte = date.today() ).filter(frequency = frequency)
      #for plan in today_plan_list
      today_plan_list = []
      for plan in today_plan_list_tmp:
          pstatus = PlanStatus.objects.filter(plan = plan).filter(updateIndex = updateIndex)
          if not pstatus:
            today_plan_list.append(plan)
       
      t = loader.get_template('myplans.html')
      c = Context({
        'today_plan_list': today_plan_list,
        'user':request.user,
        'plan_count':len(today_plan_list),
      })
      return HttpResponse(t.render(c))
  

def all_goals(request):
  if not request.user.is_authenticated():
      return HttpResponse("No access!");
  else:
      td = date.today()
      goal_list = Goal.objects.filter(user = request.user.username)#.filter(deadline__gte = date.today() )
      t = loader.get_template('allgoals.html')
      c = Context({
        'goal_list': goal_list,
        'user':request.user,
      })
      return HttpResponse(t.render(c))

def add_goal2(request):
    if not request.user.is_authenticated():
      return HttpResponse("No access!");
    else:
      goal = Goal.objects.get(id = 1)
      PlanFormSet    = inlineformset_factory(Goal, Plan, can_delete=True) 
      goal = Goal()
      goalForm = GoalForm(instance = goal)
      planFormSet = PlanFormSet(instance = goal)
      return render_to_response("goals/addall.html", {
         "goal_form": goalForm,
         "plan_formset": planFormSet,
      })

def add_goal(request, goal_id = None):

    goal_id = request.GET.get('goal_id', '')
    print goal_id
    if goal_id == "": 
       print "new goal"
       print request.user 
       goal = Goal()
       goal.user = request.user.username
    else:
        print "getting goal"
        goal = Goal.objects.get(id = goal_id)   
    if request.method == "POST":
        PlanFormSet    = inlineformset_factory(Goal, Plan, fields = "description,deadline,frequency",extra = 1, can_delete=True) 
        goalform      = GoalForm(request.POST, instance=goal)
        planformset    = PlanFormSet(request.POST, request.FILES, instance=goal)    
        if goalform.is_valid() and planformset.is_valid():
            goal = goalform.save()
            for form in planformset.forms:
               new_plan = form.save(commit = False)
               new_plan.copiedFrom = 1
               print new_plan.description
               new_plan.user = request.user.username
               new_plan.goal = goal
               new_plan.save()
               
            
            #goalform.save()
           # planformset.save()
            request.user.message_set.create(message=_("You have saved goal '%(title)s'") %  {'title': goal.title})
            #return  n HttpResponse("saved!")#reverse("goals.views.goals"))            
            return HttpResponseRedirect(reverse("goals.views.today"))            
    else:
        #goal = Goal()
        PlanFormSet    = inlineformset_factory(Goal, Plan, fields = "description,frequency,deadline",extra = 1, can_delete=True) 
        goalForm = GoalForm(instance = goal)
        planFormSet = PlanFormSet(instance = goal)
        return render_to_response("goals/addall.html", {
           "goal_form": goalForm,
           "plan_formset": planFormSet,
        })
    # generic case
    return render_to_response("goals/add.html", {
        "goal_form": goalform,
    }, context_instance=RequestContext(request)) 
def show_goal(request, goal_id = None):
    goal_id = request.GET.get('goal_id', '')
    print goal_id
    if goal_id == "": 
        return HttpResponse("No goal!");
    else:
        print "getting goal"
        thisgoal = Goal.objects.get(id = goal_id)   
    planlist = Plan.objects.filter(goal = thisgoal).filter(user = request.user.username)
    return render_to_response("goals/showgoal.html", {
        "goal": thisgoal,
        "plans": planlist,
    }, context_instance=RequestContext(request)) 
    
        
def close_plan(request, plan_id = None):
     plan_id = request.GET.get('plan_id', '')
     if not plan_id:
       return HttpResponse("No plan to update!");   
     plan = Plan.objects.get(id = plan_id)
     if plan:
       updateIndex = 0 
       if plan.frequency == 1:
           updateIndex =  datetime.now().timetuple().tm_yday    
       elif plan.frequency == 2:
           updateIndex = datetime.now().isocalendar()[1]
       pstatus = PlanStatus()
       pstatus.plan = plan
       pstatus.status = 1
       pstatus.dateUpdated = date.today()
       pstatus.updateIndex = updateIndex
       pstatus.save()
     return HttpResponseRedirect(reverse("goals.views.today"))  